<?php
/**
 * Created by PhpStorm.
 * User: wangwenfan
 * Date: 2018/8/30
 * Time: 15:40.
 */

namespace App\Admin\Controllers;

use App\Models\Base\ServerList;
use App\Models\Base\Task;
use App\Service\PlayerService;
use App\Service\ServerService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;

class TaskController extends Controller
{
    protected $server_id = 1;

    public function index()
    {
        $server_id = request()->get('server_id');
        if ($server_id) {
            $this->server_id = $server_id;
        }
        setDB($this->server_id);

        return Admin::content(function (Content $content) {
            $content->header(trans('game.data_statistic'));
            $content->description(trans('game.task_stat'));
            $content->body($this->grid());
        });
    }

    protected function grid()
    {
        return Admin::grid(Task::class, function (Grid $grid) {
            $name = ServerService::getServerName($this->server_id);
            $grid->column(trans('game.server_name'))->display(function () use ($name) {
                return $name;
            });
            $grid->id('ID');
            $grid->title(trans('game.task_name'));
            $grid->type(trans('game.task_type'));
            $grid->level(trans('game.level'));
            $self = $this;
            //进入次数
            $grid->column(trans('game.in_count'))->display(function () use ($self) {
                return PlayerService::taskEnterInfo($this->id, 1)->count();
            });
            //完成次数
            $grid->column(trans('game.complete_count'))->display(function () use ($self) {
                return PlayerService::taskEnterInfo($this->id, 3)->count();
            });
            //完成率
            $grid->column(trans('game.complete_rate'))->display(function () use ($self) {
                $enter_count = PlayerService::taskEnterInfo($this->id, 1)->count();
                $complete_count = PlayerService::taskEnterInfo($this->id, 3)->count();

                return $enter_count ? floatPercent($complete_count / $enter_count) : 0;
            });

            $grid->disableActions();
            $grid->disableCreateButton();

            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->setNotWhere(['server_id']);
                $filter->disableIdFilter();
                $filter->equal('server_id', trans('game.server_name'))->select(ServerList::all()->pluck('name', 'server_id'));
            });
        });
    }
}
